package com.itheima.consumer.web;


import com.itheima.consumer.pojo.Order;
import com.itheima.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;


@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public Order findOrderByUserId(@PathVariable("id") Long userId){
        // 1.查询用户信息
        // 1.1.准备url路径
        String url = "http://user-service/user/" + userId;
        System.out.println(url);
        // 1.2.调用RestTemplate的getForObject方法，指定url地址和返回值类型
        User user = restTemplate.getForObject(url, User.class);
        // 2.封装订单结果
        return new Order(110L, user.getId(), user.getName(), 179900L);
    }
 /*  @GetMapping("{id}")
   public Order findOrderByUserId(@PathVariable("id") Long userId){
       List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
       ServiceInstance instance = instances.get(new Random().nextInt(instances.size()));
       System.out.println(instance.getInstanceId());
       System.out.println(instance.getHost());
       System.out.println(instance.getUri());

       // 1.查询用户信息
       // 1.1.准备url路径
       String url = String.format("http://%s:%d/user/%d",instance.getHost(),instance.getPort(),userId);
       System.out.println(url);
       // 1.2.调用RestTemplate的getForObject方法，指定url地址和返回值类型
       User user = restTemplate.getForObject(url, User.class);
       // 2.封装订单结果
       return new Order(110L, user.getId(), user.getName(), 179900L);
   }*/
}